C++ Basics

Overloading methods

In some programming languages, Function overloading or method overloading is the ability to create multiple methods of the same name with different implementations. Calls to an overloaded function will run a specific implementation of that function appropriate to the context of the call, allowing one function call to perform different tasks depending on context.

For example, doTask() and doTask(object O) are overloaded methods. To call the latter, an object must be passed as a parameter, whereas the former does not require a parameter, and is called with an empty parameter field. A common error would be to assign a default value to the object in the second method, which would result in an ambiguous call error, as the compiler wouldn't know which of the two methods to use.

Rules in function overloading

  1. The overloaded method must differ either by the arity or data types.
  2. The same methods name is used for various instances of method call.

It is a classification of static polymorphism in which a function call is resolved using the 'best match technique', i.e., the function is resolved depending upon the argument list. Method overloading is usually associated with statically-typed programming languages which enforce type checking in function calls. When overloading a method, you are really just making a number of different methods that happen to have the same name. It is resolved at compile time which of these methods are used.

Example: function overloading in c++

#include <iostream>

// volume of a cube
int volume(int s)
{
    return s*s*s;
}

// volume of a cylinder
double volume(double r, int h)
{
    return 3.14*r*r*static_cast<double>(h);
}

// volume of a cuboid
long volume(long l, int b, int h)
{
    return l*b*h;
}

int main()
{
    std::cout << volume(10);
    std::cout << volume(2.5, 8);
    std::cout << volume(100, 75, 15);
}

Constructor overloading

Constructors, used to create instances of an object, may also be overloaded in some object oriented programming languages. Because in many languages the constructor’s name is predetermined by the name of the class, it would seem that there can be only one constructor. Whenever multiple constructors are needed, they are implemented as overloaded functions. In C++, default constructors take no parameters, instantiating the object members with a value zero.[1] For example, a default constructor for a restaurant bill object written in C++ might set the Tip to 15%:

Bill()
{ 
    tip = 0.15;    // percentage
    total = 0.0; 
}

By overloading the constructor, one could pass the tip and total as parameters at creation. This shows the overloaded constructor with two parameters:

Bill(double setTip, double setTotal)
{ 
    tip = setTip; 
    total = setTotal; 
}